<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>终端日志监控</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
            color: #333;
        }
        .log-container {
            display: flex;
            flex-direction: column;
            height: 100vh;
        }
        .service-log {
            flex: 1;
            border: 1px solid #ccc;
            margin-bottom: 10px;
            background-color: #fff;
            display: flex;
            flex-direction: column;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .service-title {
            font-weight: bold;
            padding: 10px;
            margin: 0;
            color: #2c3e50;
            background-color: #f8f9fa;
            border-bottom: 1px solid #eee;
            position: sticky;
            top: 0;
            z-index: 10;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .log-content {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
        }
        .log-line {
            font-family: 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.4;
            white-space: pre-wrap;
            padding: 2px 0;
        }
        .status {
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 4px;
            text-align: center;
            font-weight: bold;
        }
        .status.connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .back-link {
            display: inline-block;
            margin-bottom: 10px;
            color: #007bff;
            text-decoration: none;
            padding: 5px 10px;
            border-radius: 3px;
            background-color: #e9ecef;
        }
        .back-link:hover {
            text-decoration: underline;
            background-color: #dee2e6;
        }
        .controls {
            margin-bottom: 10px;
            display: flex;
            gap: 10px;
            align-items: center;
            flex-wrap: wrap;
        }
        .controls button {
            padding: 5px 10px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        .controls button:hover {
            background-color: #0056b3;
        }
        .controls button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .notification {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
            display: none;
        }
        .auto-refresh-control {
            display: flex;
            align-items: center;
            gap: 5px;
        }
    </style>
</head>
<body>
    <a href="../index.html" class="back-link">← 返回主页</a>
        
    <h1>终端日志监控</h1>
    <div class="controls">
        <button id="refreshBtn">刷新日志</button>
        <button id="clearAllBtn">清空所有日志</button>
        <div class="auto-refresh-control">
            <input type="checkbox" id="autoRefresh">
            <label for="autoRefresh">自动刷新(5秒)</label>
        </div>
    </div>
    <div id="notification" class="notification"></div>
    <div id="status" class="status disconnected">正在读取日志文件...</div>
    <div id="logContainer" class="log-container">
        <!-- 日志内容将根据后端返回的文件列表动态生成 -->
    </div>

    <script>
        const statusElement = document.getElementById('status');
        const refreshBtn = document.getElementById('refreshBtn');
        const clearAllBtn = document.getElementById('clearAllBtn');
        const autoRefreshCheckbox = document.getElementById('autoRefresh');
        const notificationElement = document.getElementById('notification');
        const logContainer = document.getElementById('logContainer');
        
        let autoRefreshInterval = null;
        let logFiles = {}; // 存储日志文件信息
        
        function updateStatus(message, isConnected) {
            statusElement.textContent = message;
            statusElement.className = 'status ' + (isConnected ? 'connected' : 'disconnected');
        }
        
        function showNotification(message, isError = false) {
            notificationElement.textContent = message;
            notificationElement.style.display = 'block';
            notificationElement.style.backgroundColor = isError ? '#f8d7da' : '#d1ecf1';
            notificationElement.style.color = isError ? '#721c24' : '#0c5460';
            notificationElement.style.borderColor = isError ? '#f5c6cb' : '#bee5eb';
            
            // 3秒后自动隐藏通知
            setTimeout(() => {
                notificationElement.style.display = 'none';
            }, 3000);
        }
        
        function clearLogs(service = null) {
            if (service) {
                // 清空特定服务的日志显示
                const logContainer = document.getElementById(service);
                if (logContainer) {
                    logContainer.innerHTML = '';
                }
            } else {
                // 清空所有日志显示
                document.querySelectorAll('.log-content').forEach(container => {
                    container.innerHTML = '';
                });
            }
        }
        
        async function clearAllLogsOnServer() {
            try {
                // 发送请求清空所有日志文件
                const response = await fetch(`/api/clear-log`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const result = await response.json();
                if (result.success) {
                    showNotification(result.message);
                    return true;
                } else {
                    showNotification(result.message || '清空日志失败', true);
                    return false;
                }
            } catch (error) {
                console.error('清空所有日志失败:', error);
                showNotification(`清空日志失败: ${error.message}`, true);
                return false;
            }
        }
        
        function addLogLines(service, lines) {
            const logContainer = document.getElementById(service);
            if (!logContainer) return;
            
            // 保存当前滚动位置
            const isScrolledToBottom = logContainer.scrollHeight - logContainer.clientHeight <= logContainer.scrollTop + 1;
            
            lines.forEach(line => {
                const logLine = document.createElement('div');
                logLine.className = 'log-line';
                logLine.textContent = line;
                logContainer.appendChild(logLine);
            });
            
            // 限制每个服务的日志行数，避免内存占用过大
            while (logContainer.children.length > 2000) {
                logContainer.removeChild(logContainer.firstChild);
            }
            
            // 只有当用户已经在底部时才自动滚动到底部
            if (isScrolledToBottom) {
                logContainer.scrollTop = logContainer.scrollHeight;
            }
        }
        
        async function readLogFile(service, filename) {
            try {
                const response = await fetch(`/api/get-log?file=${encodeURIComponent(filename)}`);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const result = await response.json();
                if (!result.success) {
                    throw new Error(result.message || '获取日志失败');
                }
                
                const lines = result.content.split(/\r?\n/).filter(line => line.trim() !== '');
                return lines;
            } catch (error) {
                console.error(`读取 ${service} 日志文件失败:`, error);
                return [`错误: 无法读取日志文件 ${filename}`];
            }
        }
        
        async function loadLogList() {
            try {
                const response = await fetch('/api/list-logs');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const result = await response.json();
                if (!result.success) {
                    throw new Error(result.message || '获取日志列表失败');
                }
                
                // 更新日志文件信息
                logFiles = {};
                result.logs.forEach(log => {
                    // 移除 .log 后缀作为服务名
                    const serviceName = log.name.replace(/\.log$/, '');
                    logFiles[serviceName] = log.name;
                });
                
                // 生成服务日志面板
                generateLogPanels(result.logs);
                
                return result.logs;
            } catch (error) {
                console.error('获取日志列表时出错:', error);
                throw error;
            }
        }
        
        function generateLogPanels(logs) {
            // 清空现有内容
            logContainer.innerHTML = '';
            
            // 为每个日志文件生成面板
            logs.forEach(log => {
                // 移除 .log 后缀作为服务名
                const serviceName = log.name.replace(/\.log$/, '');
                
                const serviceLogDiv = document.createElement('div');
                serviceLogDiv.className = 'service-log';
                
                const serviceTitleDiv = document.createElement('div');
                serviceTitleDiv.className = 'service-title';
                serviceTitleDiv.innerHTML = `<span>${serviceName}</span>`;
                
                const logContentDiv = document.createElement('div');
                logContentDiv.className = 'log-content';
                logContentDiv.id = serviceName;
                
                serviceLogDiv.appendChild(serviceTitleDiv);
                serviceLogDiv.appendChild(logContentDiv);
                logContainer.appendChild(serviceLogDiv);
            });
        }
        
        async function loadAllLogs() {
            updateStatus('正在读取日志文件...', false);
            
            try {
                // 如果还没有加载日志列表，先加载列表
                if (Object.keys(logFiles).length === 0) {
                    await loadLogList();
                }
                
                // 获取所有服务名
                const services = Object.keys(logFiles);
                
                // 并行读取所有日志文件
                const promises = services.map(service => 
                    readLogFile(service, logFiles[service])
                );
                
                const results = await Promise.all(promises);
                
                // 清空现有日志
                clearLogs();
                
                // 显示所有日志
                services.forEach((service, index) => {
                    addLogLines(service, results[index]);
                });
                
                updateStatus('日志文件读取完成', true);
            } catch (error) {
                console.error('读取日志文件时出错:', error);
                updateStatus('读取日志文件失败: ' + error.message, false);
            }
        }
        
        function startAutoRefresh() {
            if (autoRefreshInterval) {
                clearInterval(autoRefreshInterval);
            }
            
            autoRefreshInterval = setInterval(() => {
                loadAllLogs();
            }, 5000); // 每5秒刷新一次
        }
        
        function stopAutoRefresh() {
            if (autoRefreshInterval) {
                clearInterval(autoRefreshInterval);
                autoRefreshInterval = null;
            }
        }
        
        // 绑定按钮事件
        refreshBtn.addEventListener('click', loadAllLogs);
        
        // 绑定清空所有日志按钮事件
        clearAllBtn.addEventListener('click', async () => {
            clearLogs(); // 先清空显示
            await clearAllLogsOnServer(); // 清空服务器上的所有日志文件
            loadAllLogs(); // 重新加载（现在是空的）
        });
        
        // 绑定自动刷新切换事件
        autoRefreshCheckbox.addEventListener('change', () => {
            if (autoRefreshCheckbox.checked) {
                startAutoRefresh();
                showNotification('已启动自动刷新');
            } else {
                stopAutoRefresh();
                showNotification('已停止自动刷新');
            }
        });
        
        // 页面加载完成后读取日志
        window.addEventListener('load', async () => {
            try {
                await loadLogList(); // 先加载日志列表
                await loadAllLogs(); // 再加载日志内容
                
                // 页面加载后默认启动自动刷新
                autoRefreshCheckbox.checked = true;
                startAutoRefresh();
            } catch (error) {
                updateStatus('初始化失败: ' + error.message, false);
            }
        });
        
        // 页面关闭时清理定时器
        window.addEventListener('beforeunload', () => {
            stopAutoRefresh();
        });
    </script>
</body>
</html>